<template>
  <div class="company-report">
    <h1>科技型企业孵化器在孵（当年毕业）企业情况</h1>
    <el-form :model="form" :rules="formRules" label-width="240px" ref="ruleFormRef" style="max-width: 1200px; width: 100%">
      <!-- 企业基本信息 -->
      <el-card>
        <div slot="header" class="header">企业基本信息</div>
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
          <el-input v-model="form.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="是否高新技术企业" prop="isHighTech">
          <el-radio-group v-model="form.isHighTech">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          v-if="form.isHighTech === 1" 
          label="证书编号" 
          prop="highTechCertNo"
          :rules="formRules.highTechCertNo"
        >
          <el-input v-model="form.highTechCertNo" placeholder="请输入高新技术企业证书编号" />
        </el-form-item>
        <el-form-item label="是否科技型中小企业" prop="isTechSme">
          <el-radio-group v-model="form.isTechSme">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          v-if="form.isTechSme === 1" 
          label="登记编码" 
          prop="techSmeRegCode"
          :rules="formRules.techSmeRegCode"
        >
          <el-input v-model="form.techSmeRegCode" placeholder="请输入科技型中小企业登记编码" />
        </el-form-item>
        <el-form-item label="是否创新型中小企业" prop="isInnovativeSme">
          <el-radio-group v-model="form.isInnovativeSme">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否专精特新中小企业" prop="isSpecializedSme">
          <el-radio-group v-model="form.isSpecializedSme">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否专精特新小巨人企业" prop="isLittleGiant">
          <el-radio-group v-model="form.isLittleGiant">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>

      <!-- 企业基本情况（一） -->
      <el-card>
        <div slot="header" class="header">企业基本情况（一）</div>
        <el-form-item label="企业成立时间" prop="establishmentDate">
          <el-date-picker
              v-model="form.establishmentDate"
              type="date"
              placeholder="选择企业成立时间"
              format="YYYY-MM-DD"

          />
        </el-form-item>
        <el-form-item label="企业入驻时间" prop="settlementDate">
          <el-date-picker
              v-model="form.settlementDate"
              type="date"
              placeholder="选择企业入驻时间"
              format="YYYY-MM-DD"  />
<!--              value-format="YYYY-MM-DD HH:mm:ss"-->

        </el-form-item>
        <el-form-item label="企业登记注册类型" prop="registrationType">
          <el-select v-model="form.registrationType" placeholder="请选择企业登记注册类型">
            <el-option
                v-for="item in registrationTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
<!--          <span v-if="form.registrationType">{{ registrationTypeMap[form.registrationType] }}</span>-->
        </el-form-item>
        <el-form-item label="企业所属技术领域" prop="techField">
          <el-select v-model="form.techField" placeholder="请选择企业所属技术领域">
            <el-option
                v-for="item in techFieldOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
<!--          <span v-if="form.techField">{{ techFieldMap[form.techField] }}</span>-->
        </el-form-item>
        <el-form-item label="企业核心技术所属《国家重点支持的高新技术领域》" prop="keyTechField">
          <el-input v-model="form.keyTechField" placeholder="请输入核心技术领域代码" />
        </el-form-item>
        <el-form-item label="行业类别" prop="industryCategory">
          <el-input v-model="form.industryCategory" placeholder="请输入四位数的行业类别代码" />
        </el-form-item>
        <el-form-item label="是否与创业导师建立辅导关系" prop="mentorshipRelation">
          <el-radio-group v-model="form.mentorshipRelation">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业纳税人类型" prop="taxpayerType">
          <el-radio-group v-model="form.taxpayerType">
            <el-radio :label="1">一般纳税人</el-radio>
            <el-radio :label="0">小规模纳税人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主要负责人性别" prop="principalGender">
          <el-radio-group v-model="form.principalGender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否毕业企业" prop="isGraduated">
          <el-radio-group v-model="form.isGraduated">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isGraduated === 1" label="是否被兼并或收购" prop="isMergedAcquired">
          <el-radio-group v-model="form.isMergedAcquired">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isGraduated === 1" label="是否在国内外资本市场挂牌、上市" prop="isListed">
          <el-radio-group v-model="form.isListed">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业主要负责人创业特征" prop="entrepreneurType">
          <el-select v-model="form.entrepreneurType" placeholder="请选择企业主要负责人创业特征">
            <el-option label="大学生创业" value="1" />
            <el-option label="留学归国人员" value="2" />
            <!-- 其他选项 -->
          </el-select>
        </el-form-item>
      </el-card>

      <!-- 企业经济概况 -->
      <el-card>
        <div slot="header" class="header">企业经济概况</div>
        <el-form-item label="在孵企业总收入（千元）" prop="totalIncome">
          <el-input-number v-model="form.totalIncome" :min="0" placeholder="请输入在孵企业总收入" />
        </el-form-item>
        <el-form-item label="在孵企业净利润（千元）" prop="netProfit">
          <el-input-number v-model="form.netProfit" :min="0" placeholder="请输入在孵企业净利润" />
        </el-form-item>
        <el-form-item label="在孵企业出口总额（千元）" prop="exportVolume">
          <el-input-number v-model="form.exportVolume" :min="0" placeholder="请输入在孵企业出口总额" />
        </el-form-item>
        <el-form-item label="在孵企业研究与试验发展（R&D）经费支出（千元）" prop="rdExpenditure">
          <el-input-number v-model="form.rdExpenditure" :min="0" placeholder="请输入R&D经费支出" />
        </el-form-item>
        <el-form-item label="在孵企业实际上缴税费（千元）" prop="taxPayment">
          <el-input-number v-model="form.taxPayment" :min="0" placeholder="请输入实际上缴税费" />
        </el-form-item>
      </el-card>

      <!-- 企业从业人员情况 -->
      <el-card>
        <div slot="header" class="header">企业从业人员情况</div>
        <el-form-item label="在孵企业从业人员（人）" prop="employees">
          <el-input-number v-model="form.employees" :min="0" placeholder="请输入在孵企业从业人员数" />
        </el-form-item>
        <el-form-item label="其中：博士（人）" prop="doctorNum">
          <el-input-number v-model="form.doctorNum" :min="0" placeholder="请输入博士人数" />
        </el-form-item>
        <el-form-item label="大专以上（人）" prop="collegeAbove">
          <el-input-number v-model="form.collegeAbove" :min="0" placeholder="请输入大专以上人数" />
        </el-form-item>
        <el-form-item label="其中：吸纳应届大学毕业生（人）" prop="freshGraduate">
          <el-input-number v-model="form.freshGraduate" :min="0" placeholder="请输入吸纳应届大学毕业生人数" />
        </el-form-item>
        <el-form-item label="留学人员（人）" prop="returnee">
          <el-input-number v-model="form.returnee" :min="0" placeholder="请输入留学人员数" />
        </el-form-item>
      </el-card>

      <!-- 企业知识产权情况 -->
      <el-card>
        <div slot="header" class="header">企业知识产权情况</div>
        <el-form-item label="当年知识产权申请数（件）" prop="ipApplication">
          <el-input-number v-model="form.ipApplication" :min="0" placeholder="请输入当年知识产权申请数" />
        </el-form-item>
        <el-form-item label="当年知识产权授权数（件）" prop="ipGranted">
          <el-input-number v-model="form.ipGranted" :min="0" placeholder="请输入当年知识产权授权数" />
        </el-form-item>
        <el-form-item label="其中：发明专利（件）" prop="inventionPatentGranted">
          <el-input-number v-model="form.inventionPatentGranted" :min="0" placeholder="请输入发明专利授权数" />
        </el-form-item>
        <el-form-item label="拥有有效知识产权数（件）" prop="validIp">
          <el-input-number v-model="form.validIp" :min="0" placeholder="请输入拥有有效知识产权数" />
        </el-form-item>
        <el-form-item label="其中：发明专利（件）" prop="validInventionPatent">
          <el-input-number v-model="form.validInventionPatent" :min="0" placeholder="请输入有效发明专利数" />
        </el-form-item>
        <el-form-item label="软件著作权（件）" prop="softwareCopyright">
          <el-input-number v-model="form.softwareCopyright" :min="0" placeholder="请输入软件著作权数" />
        </el-form-item>
        <el-form-item label="植物新品种（个）" prop="plantVariety">
          <el-input-number v-model="form.plantVariety" :min="0" placeholder="请输入植物新品种数" />
        </el-form-item>
        <el-form-item label="集成电路布图（个）" prop="icLayout">
          <el-input-number v-model="form.icLayout" :min="0" placeholder="请输入集成电路布图数" />
        </el-form-item>
        <el-form-item label="购买国外专利（件）" prop="foreignPatentPurchase">
          <el-input-number v-model="form.foreignPatentPurchase" :min="0" placeholder="请输入购买国外专利数" />
        </el-form-item>
      </el-card>

      <!-- 企业科技活动情况 -->
      <el-card>
        <div slot="header" class="header">企业科技活动情况</div>
        <el-form-item label="技术合同成交数量（项）" prop="techContractNum">
          <el-input-number v-model="form.techContractNum" :min="0" placeholder="请输入技术合同成交数量" />
        </el-form-item>
        <el-form-item label="技术合同成交额（千元）" prop="techContractAmount">
          <el-input-number v-model="form.techContractAmount" :min="0" placeholder="请输入技术合同成交额" />
        </el-form-item>
        <el-form-item label="当年承担国家级科技计划项目数（项）" prop="nationalTechProject">
          <el-input-number v-model="form.nationalTechProject" :min="0" placeholder="请输入国家级科技计划项目数" />
        </el-form-item>
      </el-card>

      <!-- 其他信息 -->
      <el-card>
        <div slot="header" class="header">其他信息</div>
        <el-form-item label="获得投融资金额（千元）" prop="financingAmount">
          <el-input-number v-model="form.financingAmount" :min="0" placeholder="请输入获得投融资金额" />
        </el-form-item>
        <el-form-item label="其中：获得孵化器孵化基金投资额（千元）" prop="incubatorFundInvestment">
          <el-input-number v-model="form.incubatorFundInvestment" :min="0" placeholder="请输入孵化器基金投资额" />
        </el-form-item>
        <el-form-item label="其中：获银行贷款额（千元）" prop="bankLoan">
          <el-input-number v-model="form.bankLoan" :min="0" placeholder="请输入银行贷款额" />
        </el-form-item>
        <el-form-item label="占用孵化器场地面积（平方米）" prop="occupyingArea">
          <el-input-number v-model="form.occupyingArea" :min="0" placeholder="请输入占用场地面积" />
        </el-form-item>
        <el-form-item label="企业成立时注册资本（千元）" prop="registeredCapital">
          <el-input-number v-model="form.registeredCapital" :min="0" placeholder="请输入注册资本" />
        </el-form-item>
      </el-card>

<!--      &lt;!&ndash; 填报信息 &ndash;&gt;-->
<!--      <el-card>-->
<!--        <div slot="header" class="header">填报信息</div>-->
<!--        <el-form-item label="单位详细名称" prop="companyPrincipal">-->
<!--          <el-input v-model="form.companyPrincipal" placeholder="请输入单位负责人姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="统计负责人" prop="statisticsPrincipal">-->
<!--          <el-input v-model="form.statisticsPrincipal" placeholder="请输入统计负责人姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="填表人" prop="filler">-->
<!--          <el-input v-model="form.filler" placeholder="请输入填表人姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="联系电话" prop="contactPhone">-->
<!--          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="报出日期" prop="reportDate">-->
<!--          <el-date-picker v-model="form.reportDate" type="date" placeholder="选择报出日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />-->
<!--        </el-form-item>-->
<!--      </el-card>-->

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="saveDraft">保存草稿</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import {AddDataHatchYear, UpdataUserDataHatchYear,  GetDataHatchYearid} from '@/api/enterpeise';
import { getLoginUserId } from '@/utils/storage';
import { useRoute } from 'vue-router';
import router from "@/router";

const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isSubmit = ref(false);
const totalRecord = ref(0);

// 表单数据
const form = reactive({
  userId: getLoginUserId(), // 自动填充当前登录用户ID
  status: 0, // 默认状态为保存
  companyName: '',
  unifiedSocialCreditCode: '',
  isHighTech: 0,
  highTechCertNo: '',
  isTechSme: 0,
  techSmeRegCode: '',
  isInnovativeSme: 0,
  isSpecializedSme: 0,
  isLittleGiant: 0,
  establishmentDate: '',
  settlementDate: '',
  registrationType: '',
  techField: '',
  keyTechField: '',
  industryCategory: '',
  mentorshipRelation: 0,
  taxpayerType: 0,
  principalGender: 0,
  isGraduated: 0,
  isMergedAcquired: 0,
  isListed: 0,
  entrepreneurType: '',
  financingAmount: 0,
  incubatorFundInvestment: 0,
  bankLoan: 0,
  occupyingArea: 0,
  registeredCapital: 0,
  totalIncome: 0,
  netProfit: 0,
  exportVolume: 0,
  rdExpenditure: 0,
  taxPayment: 0,
  employees: 0,
  doctorNum: 0,
  collegeAbove: 0,
  freshGraduate: 0,
  returnee: 0,
  ipApplication: 0,
  ipGranted: 0,
  inventionPatentGranted: 0,
  validIp: 0,
  validInventionPatent: 0,
  softwareCopyright: 0,
  plantVariety: 0,
  icLayout: 0,
  foreignPatentPurchase: 0,
  techContractNum: 0,
  techContractAmount: 0,
  nationalTechProject: 0,
  companyPrincipal: '',
  statisticsPrincipal: '',
  filler: '',
  contactPhone: '',
  reportDate: ''
});
// 定义企业登记注册类型映射
const registrationTypeMap = {
  '110': '国有',
  '120': '集体',
  '130': '股份合作',
  '141': '国有联营',
  '142': '集体联营',
  '143': '国有与集体联营',
  '149': '其他联营',
  '151': '国有独资公司',
  '159': '其他有限责任公司',
  '160': '股份有限公司',
  '171': '私营独资',
  '172': '私营合伙',
  '173': '私营有限责任公司',
  '174': '私营股份有限公司',
  '190': '其他',
  '210': '与港澳台商合资经营',
  '220': '与港澳台商合作经营',
  '230': '港澳台商独资',
  '240': '港澳台商投资股份有限公司',
  '290': '其他港澳台投资',
  '310': '中外合资经营',
  '320': '中外合作经营',
  '330': '外资企业',
  '340': '外商投资股份有限公司',
  '390': '其他外商投资'
};
// 生成企业登记注册类型选项
const registrationTypes = Object.entries(registrationTypeMap).map(([value, label]) => ({
  value,
  label
}));
// 定义企业所属技术领域映射
const techFieldMap = {
  '1': '电子信息',
  '2': '先进制造',
  '3': '航空航天',
  '4': '现代交通',
  '5': '生物医药与医疗器械',
  '6': '新材料',
  '7': '新能源与节能',
  '8': '环境保护',
  '9': '地球、空间与海洋',
  '10': '核应用技术',
  '11': '现代农业',
  '12': '文化创意'
};
// 生成企业所属技术领域选项
const techFieldOptions = Object.entries(techFieldMap).map(([value, label]) => ({
  value,
  label
}));
// 表单验证规则
const formRules = reactive<FormRules>({
  companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  unifiedSocialCreditCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
  isHighTech: [{ required: true, message: '请选择是否高新技术企业', trigger: 'change' }],
  highTechCertNo: [{
    required: true,
    message: '请输入高新技术企业证书编号',
    trigger: 'blur'
  }, {
    validator: (rule: any, value: string, callback: any) => {
      if (form.isHighTech === 1 && !value) {
        callback(new Error('请选择"是"时必须填写证书编号'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  isTechSme: [{ required: true, message: '请选择是否科技型中小企业', trigger: 'change' }],
  techSmeRegCode: [{
    required: true,
    message: '请输入科技型中小企业登记编码',
    trigger: 'blur'
  }, {
    validator: (rule: any, value: string, callback: any) => {
      if (form.isTechSme === 1 && !value) {
        callback(new Error('请选择"是"时必须填写登记编码'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  establishmentDate: [{ required: true, message: '请选择企业成立时间', trigger: 'change' }],
  settlementDate: [{ required: true, message: '请选择企业入驻时间', trigger: 'change' }],
  registrationType: [{ required: true, message: '请选择企业登记注册类型', trigger: 'change' }],
  techField: [{ required: true, message: '请选择企业所属技术领域', trigger: 'change' }],
  industryCategory: [
    { required: true, message: '请输入行业类别代码', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '行业类别代码必须是四位数字', trigger: 'blur' },
    { required: true, message: '请选择行业类别', trigger: 'change' }
  ],

 // reportDate: [{ required: true, message: '请选择报出日期', trigger: 'change' }],
  // companyPrincipal: [{ required: true, message: '请输入单位负责人姓名', trigger: 'blur' }],
  // statisticsPrincipal: [{ required: true, message: '请输入统计负责人姓名', trigger: 'blur' }],
  // filler: [{ required: true, message: '请输入填表人姓名', trigger: 'blur' }],
  // contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
});

// 获取用户未提交的报表数据
const getUserDraft = async (id: number)=> {
  try{
    const res = await GetDataHatchYearid(id);
    if (res.code === 200) {
      console.log(res.data);
      Object.assign(form, res.data);
    }
  } catch (error) {
    console.error('获取报表数据失败:', error);
    ElMessage.error('获取报表数据失败');
  }
};

// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return;



  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let response;
        form.status = 1; // 设置状态为提交
        if (totalRecord.value === 1) {
          // 如果存在未提交记录，则调用更新接口
          response = await UpdataUserDataHatchYear(form);
        } else {
          // 否则调用添加接口
          response = await AddDataHatchYear(form);
        }

        if (response.code === 200) {
          ElMessage.success('提交成功');
          isSubmit.value = true;
          router.push(`/personal-center/fill-information/my-datafrom`);
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
        router.push(`/personal-center/fill-information/my-datafrom`);
      }
    } else {
      ElMessage.warning('表单没有填写完整');
    }
  });
};

// 保存草稿
const saveDraft = async () => {
  if (!ruleFormRef.value) return;

  form.status = 0; // 设置状态为保存
console.log(form);
  try {
    let response;
    if (totalRecord.value === 1) {
      // 如果存在未提交记录，则调用更新接口
      response = await UpdataUserDataHatchYear(form);
    } else {
      // 否则调用添加接口
      response = await AddDataHatchYear(form);
    }

    if (response.code === 200) {
      ElMessage.success('草稿保存成功');
      isSubmit.value = false;
    } else {
      ElMessage.error('保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 重置表单
const resetForm = () => {
  ruleFormRef.value?.resetFields();
  isSubmit.value = false;
};

onMounted(() => {
  const id = route.query.id;
  if (id) {
    totalRecord.value = 1;
    getUserDraft(Number(id)); // 页面加载时获取需要的报表数据
  }
});
</script>

<style lang="scss" scoped>
.header {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}
.el-card {
  margin: 20px auto;
}
.company-report {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-table th, .el-table td) {
    font-weight: bold;
  }
}
</style>
